package com.xiyu.service.framework.postOffice.sync;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.xiyu.service.framework.postOffice.factory.PostOfficeFactory;
import com.xiyu.service.framework.postOffice.service.PostOfficeService;
import com.xiyu.service.model.mailbox.mail.MailboxMail;
import com.xiyu.service.model.mailbox.mail.MailboxMailErrorLogDraft;
import com.xiyu.service.repository.mailbox.mail.MailboxMailErrorLogRepository;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.concurrent.CompletableFuture;

@Component
public class SyncSaveMail {
    @Resource
    private PostOfficeFactory postOfficeFactory;

    @Resource
    MailboxMailErrorLogRepository mailboxMailErrorLogRepository;

    @Async
    public CompletableFuture<Void> saveMail(MailboxMail mail){
        try {
            PostOfficeService postOfficeService = postOfficeFactory.getInstance(mail.accountId());
            postOfficeService.saveMail(mail.id());
            postOfficeService.close();
        }catch (Exception e){
            mailboxMailErrorLogRepository.insert(MailboxMailErrorLogDraft.$.produce(draft ->
                    draft.setAccountId(mail.accountId()).setMailId(mail.id()).setFolderId(mail.folderId())
                            .setUid(mail.uid()).setMessage(e.getMessage())
                            .setStackTraceInfo(ExceptionUtil.stacktraceToString(e, 30000))
            ));
        }
        return CompletableFuture.completedFuture(null);
    }
}
